package com.kinon.ceshiaccount.fragment.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.ceshiaccount.R;
import com.kinon.ceshiaccount.activity.OrderDetailActivity;
import com.kinon.ceshiaccount.adapter.KeyAdapter;
import com.kinon.ceshiaccount.application.AccountApplication;
import com.kinon.ceshiaccount.bean.OrderDetailBean;
import com.kinon.ceshiaccount.bean.urgent.U_OrderBean;
import com.kinon.ceshiaccount.constant.Constant;
import com.kinon.ceshiaccount.fragment.BaseFragment;
import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.network.StrCallback;
import com.kinon.ceshiaccount.util.LoadDialogManager;
import com.kinon.ceshiaccount.util.SPManage;
import com.kinon.ceshiaccount.view.itemdecoration.MyItemDecoration;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by luohao on 2017-06-16.
 * 取餐
 */

public class TakeMealFragment extends BaseFragment
        implements KeyAdapter.OnRecyclerClickListener, View.OnClickListener {

    private View mView;
    /**
     * 取餐二维码
     */
    private EditText et_makemealId;
    /**
     * 手动输入的编码
     */
    private EditText et_sousuo;

    private RecyclerView recycler_key;
    private TextView btn_1, btn_2, btn_3,
            btn_4, btn_5, btn_6,
            btn_7, btn_8, btn_9,
            btn_0, btn_00, btn_p,
            btn_clear, btn_complete;
    /**
     * 数字按键的适配器
     */
    private KeyAdapter adapter;
    /**
     * 按键上的数字数组
     */
    private String key[] = {"7", "8", "9", "4", "5", "6", "1", "2", "3", "0", "00", "."};
    /**
     * 显示的数字
     */
    private String makemealCode = "";

    private Context context;
    private Gson gson = null;
    private TextWatcher Watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence text, int start,
                                  int icount, int iafter) {
            if (start == 15) {
                String qrcode = text.toString();
                if (!Constant.URGENT_TYPE) {
                    getOrderDetail(0, qrcode);
                } else {
                    urgent(qrcode);
                }
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_takemeal_layout, container, false);
        return mView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();

    }

    private void initView() {
        context = AccountApplication.getInstance();
        gson = new Gson();
        et_makemealId = (EditText) mView.findViewById(R.id.et_makemealId);
        et_sousuo = (EditText) mView.findViewById(R.id.et_sousuo);
        recycler_key = (RecyclerView) mView.findViewById(R.id.recycler_key);

        btn_clear = (Button) mView.findViewById(R.id.btn_clear);
        btn_complete = (Button) mView.findViewById(R.id.btn_complete);

        addOnclick();
        setRecycler();
    }

    /**
     * 绑定监听事件
     */
    private void addOnclick() {
        et_makemealId.requestFocus();
        et_makemealId.addTextChangedListener(Watcher);
        btn_clear.setOnClickListener(this);
        btn_complete.setOnClickListener(this);
    }

    /**
     * 给recyclerview设置值
     */
    private void setRecycler() {
        GridLayoutManager gManager = new GridLayoutManager(getActivity(), 3);
        recycler_key.setLayoutManager(gManager);
        recycler_key.addItemDecoration(new MyItemDecoration(15, 15,
                getResources().getColor(R.color.white)));

        adapter = new KeyAdapter(key, getActivity());
        recycler_key.setAdapter(adapter);
        /**绑定点击监听事件*/
        adapter.setOnItemClickListener(this);
    }

    /**
     * recyclerview的监听事件
     */
    @Override
    public void onItemClick(View view, int position) {
        makemealCode += key[position];
        et_sousuo.setText(makemealCode);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_clear:
                makemealCode = "";
                et_sousuo.setText(makemealCode);
                break;
            case R.id.btn_complete:
                if (!Constant.URGENT_TYPE) {
                    complete();
                } else {
                    urgent(makemealCode);
                }
                break;
        }
    }

    private void urgent(String no) {
        ArrayList<U_OrderBean> uOlist = null;
        if (no.length() == 16) {
            uOlist = (ArrayList<U_OrderBean>)
                    DataSupport.where("orderno=?", no)
                            .find(U_OrderBean.class, true);
        } else {
            uOlist = (ArrayList<U_OrderBean>)
                    DataSupport.where("dayno=?", no)
                            .find(U_OrderBean.class, true);
        }
//        int uOlistNum=DataSupport.where("dayno=?",no).count(U_OrderBean.class);
        if (null != uOlist && uOlist.size() > 0) {
            Intent intent = new Intent(getContext(), OrderDetailActivity.class);
            intent.putExtra("uOlist", uOlist);
            startActivity(intent);
            clearEdit();
        } else {
            Toast.makeText(context, "本地没有查询到订单为" + makemealCode + "的信息",
                    Toast.LENGTH_SHORT).show();
        }
        clearEdit();
    }

    private void clearEdit() {
        makemealCode = "";
        et_sousuo.setText(makemealCode);
        et_makemealId.setText(makemealCode);
    }

    /**
     * 点击完成进入的方法
     */
    private void complete() {
        if (TextUtils.isEmpty(makemealCode)) {
            return;
        }
        getOrderDetail(1, makemealCode);

    }

    private void getOrderDetail(final int idType, String qrcode) {
        makemealCode = "";
        et_makemealId.setText(makemealCode);
        et_sousuo.setText(makemealCode);
        LoadDialogManager.gerInstnce().showProgressDialog(getActivity(), "加载中...");
        Call<String> call = null;
        if (idType == 0) {
            call = HttpManage.getRequestApi()
                    .getDetail(SPManage.getInstance().getToken(), qrcode, "", "");
        } else {
            call = HttpManage.getRequestApi()
                    .getDetail(SPManage.getInstance().getToken(), "", qrcode, "");
        }
        if (call == null) {
            return;
        }
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String base) {
                LoadDialogManager.gerInstnce().dismissProgressDialog();
                Gson gson = new Gson();
                OrderDetailBean orderDatai = gson.fromJson(base, OrderDetailBean.class);
//                BaseBean bean=response.body();
                Intent intent = new Intent(getContext(), OrderDetailActivity.class);
                intent.putExtra("idType", idType);
                intent.putExtra("orderdetail", orderDatai);
                startActivity(intent);
            }

            @Override
            public void onError(int code, String error) {
                LoadDialogManager.gerInstnce().dismissProgressDialog();
                Toast.makeText(context, error, Toast.LENGTH_SHORT).show();
            }
        });

    }
}
